/**
 * Copyright 2007-2008. Chongqing First Information & Network Co., Ltd. All
 * rights reserved. <a>http://www.cqfirst.com.cn</a>
 */
package com.cqcis.uip.base.framework.base.impl;

import com.cqcis.uip.base.framework.base.AbstractConnectorSupport;
import com.cqcis.uip.base.framework.common.Role;
import com.cqcis.uip.base.framework.core.RegisteredServiceContext;
import com.cqcis.uip.base.framework.core.ServiceRole;
import com.cqcis.uip.base.framework.core.ServiceRoleIgnore;
import com.cqcis.uip.base.framework.core.impl.ConnectorServiceAdaptor;
import com.cqcis.uip.base.framework.handlers.impl.DefaultClientHandler;

/**
 * @author huangmy
 * @date   2007-12-18
 */
@ServiceRoleIgnore
public class DefaultConnector extends AbstractConnectorSupport {
	private static final long serialVersionUID = 1L;
    private ConnectorServiceAdaptor serviceAdaptor;
    
    @Override
    public void start(RegisteredServiceContext serviceContext) throws Exception {
    	init(); // init first
    	
    	super.start(serviceContext);
    }
    
    /**
     * handler
     * 
     * @return
     */
    protected DefaultClientHandler getClientHandler() {
    	return new DefaultClientHandler();
    }
    
    private void init() {
    	DefaultClientHandler handler = getClientHandler();
    	
    	handler.setAfterService(serviceAdaptor.getAfterService());//后处理
    	handler.setService(serviceAdaptor.getService());// 业务层处理
    	handler.registerCloseSessionIfTimeout(serviceAdaptor.isCloseSessionIfTimeout());
    	
    	setHandler(handler);
    	
    	setDecoder(serviceAdaptor.getObjectDecoder()); //读数据解码器 
    	setEncoder(serviceAdaptor.getObjectEncoder()); //写数据编码器
    	
    	if (serviceAdaptor.getReadFilters() != null) {
    		setReadFilters(serviceAdaptor.getReadFilters());
    	}
    	
    	if (serviceAdaptor.getWriteFilters() != null) {
    		setWriteFilters(serviceAdaptor.getWriteFilters());
    	}    	
    	
    	setStreamRecord(serviceAdaptor.isDefaultStreamRecord());
    }
	
	@Override
	protected void doStart() throws Exception {
		// do nothing
	}

	@Override
	protected void doStop() throws Exception {
		// do nothing
	}
    
	@ServiceRole(Role.SOCKET_CLIENT)
	public void setServiceAdaptor(ConnectorServiceAdaptor serviceAdaptor) {
		this.serviceAdaptor = serviceAdaptor;
	}	
}
